import time
import random
import serial
from tool import log


def open_com(cfg):
    try:
        ser = serial.Serial()
        ser.port = cfg["port"]
        ser.baudrate = cfg["rate"]
        ser.bytesize = serial.EIGHTBITS
        ser.parity = serial.PARITY_NONE
        ser.stopbits = serial.STOPBITS_ONE
        ser.timeout = None

        ser.open()

        ser.write(b"q")
        ser.flush()

        ser.read_all()

        return ser
    except Exception as e:
        log("serial error: %s" % e)

    return None


def read_com(k, ser, que):
    try:
        if not ser:
            return

        ser.write(b"K")
        ser.flush()

        data = ser.read_all()

        data = "%s" % data

        pos = data.find("ACK")
        if pos >= 0:
            return

        data = data.replace("\\n", "")

        data = data.split("\\r")

        for d in data:
            if len(d) < 5:
                continue

            val = float(d)

            que.put({k: val})
    except Exception as e:
        log("read_com error: %s" % e)


def do_test(k, que):
    while True:
        a = random.randint(1, 100)
        que.put({k: a * 1000})

        time.sleep(1)


def do_com(cfg, k, que):
    # for test=====
    # do_test(k, que)
    # return

    ser = open_com(cfg[k])

    if not ser:
        log("open com error")
        return

    while True:
        try:
            read_com(k, ser, que)
        except Exception as e:
            log("do_com error: %s" % e)

        time.sleep(0.1)
